<template>
  <div class="main" style="margin-right: -90px">
    <div class="">
      <div class="ml-5 mt-4"><span style="color:#5b5b5b;font-weight: bold;font-size: 30px;" >
            全 国 硕 士 研 究 生 招 生 考 试 进 入 复 试 的 初 试 成 绩 基 本 要 求</span>
      </div>
      <div class="row mt-1 ml-5">
        <div class="col-md-8">
          <el-menu router
                   :default-active="$route.path"
                   style="border-radius: 5px;"
                   text-color="#939aa2"
                   active-text-color="#0f5da2"
                   class="el-menu-demo"
                   mode="horizontal"
                   @select="handleSelect">

            <el-menu-item index="/Main/Colleges_Main/College_Grade/Academic_Grades"
                          :route="{name:'Academic_Grades',query:{grades_sort:1,grades_year:this.find_year}}">
              <span class="titlefontclass">学术学位</span>
            </el-menu-item>

            <el-menu-item index="/Main/Colleges_Main/College_Grade/Profession_Grades"
                          :route="{name:'Profession_Grades',query:{grades_sort:2,grades_year:this.find_year}}">
              <span class="titlefontclass">专业学位</span>
            </el-menu-item>

            <el-menu-item>
              <el-select v-model="find_year" @change="selectChanged">
                <el-option v-for="(grades) in all_years" :label="grades.grades_year"
                           :value="grades.grades_year"
                           :key="grades.grades_year"></el-option>
              </el-select>
            </el-menu-item>

          </el-menu>
        </div>
        <div class="col-md-4 mt-3">
          <el-button type="primary" @click="addOpen()" plain><i class="el-icon-plus pr-2" ></i>添加</el-button>
<!--          <el-button type="danger" @click="Delete()" plain><i class="el-icon-delete pr-2" ></i>删除</el-button>-->
        </div>
        <!--添加弹窗-->
        <el-dialog
            title="添加分数线信息"
            :visible.sync="addialogVisible"
            width="50%"
            @close="handleClose">

          <!--        添加表单-->
          <el-form ref="Addform" :model="Addform" label-width="120px" :rules="rules" :before-close="closeDiv">

            <el-row>
              <el-col :span="12">
                <el-form-item label="年份：" :label-width="formLabelWidth" prop="grades_year">
                  <el-select v-model="Addform.grades_year">
                    <el-option v-for="(grades) in select_years" :label="grades.label"
                               :value="grades.value"
                               :key="grades.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">

                <el-form-item label="类别：" :label-width="formLabelWidth" prop="grades_sort">
                  <el-select v-model="Addform.grades_sort">
                    <el-option v-for="(sort) in sorts" :label="sort.label"
                               :value="sort.value"
                               :key="sort.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

            </el-row>


            <el-form-item label="图片：" :label-width="formLabelWidth" prop="grades_img">

              <el-upload ref="upload"
                         name="upload"
                         action="#"
                         drag
                         :file-list="fileList"
                         list-type="picture"
                         :limit="1"
                         :on-exceed="handleExceed"
                         :auto-upload="false"
                         :on-remove="handleRemove"
                         :on-change="imgChange">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>

            </el-form-item>




          </el-form>

          <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitAdd('Addform')">添 加</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
        </el-dialog>




      </div>
    </div>
    <div class="img_main">
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
import {getAllYears} from '@/api/College'


export default {
name: "college_grade",
  data(){
    return{
      grades_sort:1,
      find_year:2022,
      sorts:[
        {
          id:1,
          label:'学术学位',
          value:1
        },
        {
          id:2,
          label:'专业学位',
          value:2
        },
      ],
      //  添加弹窗相关
      addialogVisible:false,
      Addform:{
        grades_sort:'',
        grades_year:'',
      },
      formLabelWidth: '100px',
      //编辑表单验证规则
      rules: {
        grades_sort: [
          {required: true, message: '请选择年份', trigger: 'change'}
        ],
        grades_year: [
          {required: true, message: '请选择专业类别', trigger: 'change'}
        ],
      },
      fileList:[],
      file:[],
      all_years:[],
      select_years:[
        {
          label:'2019',
          value:2019
        },
        {
          label:'2020',
          value:2020
        },
        {
          label:'2021',
          value:2021
        },
        {
          label:'2022',
          value:2022
        },
        {
          label:'2023',
          value:2023
        },
        {
          label:'2024',
          value: 2024
        },



      ]







    }
  },
  methods:{
    cancel() {
      this.addialogVisible = false;
      // 点击取消按钮的时候清除输入框中的内容 清除验证
      //  this.$nextTick获取了节点之后进行操作
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });
      this.fileList = [];  //将列表清空
      this.fileList.length = 0;
      this.$refs.upload.clearFiles();

    },
    openCancelEdit(){
      this.editdialogVisible = false;
    },
    // 右上角 × 取消按钮
    closeDiv() {

      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });
      this.fileList = [];  //将列表清空
      this.fileList.length = 0;
      this.$refs.upload.clearFiles();

    },
    handleClose(){
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });
      this.fileList = [];  //将列表清空
      this.fileList.length = 0;
      this.$refs.upload.clearFiles();

    },
    //打开添加的弹窗
    addOpen(){

      this.addialogVisible=true;

    },
    submitAdd(formName){

      //验证
      this.$refs[formName].validate((valid) => {
        if (valid) {

          //再次确认
          this.$confirm('确认添加?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            this.addSave();

          }).catch(() => {
            this.$msg.error("添加失败！");
          });

        } else {
          this.$msg.error("添加失败！");
          return false;
        }
      });


    },
    //连接后端 添加
    async addSave(){

      if(this.fileList.length==0){
        this.$msg.warning("请上传图片！");
        return false;
      }
      let formData = new FormData();
      formData.append('grades_img', this.fileList[0].raw);

      formData.append('grades_sort',this.Addform.grades_sort);
      formData.append('grades_year',this.Addform.grades_year);

      // console.log(formData);

      this.$ajax({
        url: "/api/college/addGrades",
        method: "post",
        dataType:'text',
        cache:  false , //上传文件无需缓存
        processData:  false , //用于对data参数进行序列化处理 这里必须false
        contentType:  false ,  //
        data: formData
      }).then((result)=>{

        if (result.data.code == 1) {
          this.$msg.success("发布成功！");
        }
        else if(result.data.code==2){
          this.$msg.error('该年份、类别的国家分数线已添加！');
        }else{
          this.$msg.error('发布失败！');
        }
      });

      this.$refs.upload.clearFiles();
      this.addialogVisible=false;
      this.init();


    },
    //  文件上传相关
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      this.fileList = [];  //将列表清空
      this.fileList.length = 0;
      fileList=[];
      fileList.length=0;
      this.$refs.upload.clearFiles();
    },
    //  点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
    },
    //限制上传数量
    handleExceed (file, fileList) {
      this.$msg.warning('只能上传一张图片！');
    },
    //限制用户上传的图片格式和大小。
    imgChange (file,fileList) {

      this.fileList = fileList;
      var img_type = file.name.substring(file.name.lastIndexOf('.') + 1)
      var imgSize = file.size;
      var img_maxsize = 1024 * 500;

      console.log(img_type=='jpg');

      if ((img_type != 'jpg') && (img_type != 'png') && (img_type != 'JPG') && (img_type != 'JPEG') && (img_type != 'jpeg')) {
        this.fileList = [];  //将列表清空
        this.$message.warning('上传图片只能是JPG或PNG或JPEG格式!');
        return false;
      }

      if (imgSize>img_maxsize) {
        this.fileList = [];  //将列表清空
        this.$message.warning('上传图片大小不能超过500KB!');
        return false;
      }

      return true;
      //this.$refs.uploadElement.clearValidate();

    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    selectChanged(val){

      this.find_year = val;
      if(this.$router.history.current.path =='/Main/Colleges_Main/College_Grade/Profession_Grades'){
        this.grades_sort=1;
        this.$router.push({
          path:'/Main/Colleges_Main/College_Grade/Academic_Grades',
          query:{
            grades_year:this.find_year,
            grades_sort:this.grades_sort,
          }

        });

      }else if(this.$router.history.current.path =='/Main/Colleges_Main/College_Grade/Academic_Grades'){

        this.grades_sort=2;
        this.$router.push({
          path:'/Main/Colleges_Main/College_Grade/Profession_Grades',
          query:{
            grades_year:this.find_year,
            grades_sort:this.grades_sort,
          }

        });

      }

    },
    init(){
      getAllYears({}).then(res=>{
        this.all_years=res.data.years;
      })
    },
    //删除
    // Delete(){
    //   //再次确认
    //   this.$confirm('确认删除该分数线信息吗？', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //
    //     this.delete_main();
    //
    //
    //   }).catch(() => {
    //     this.$msg.error("取消删除！");
    //   });
    // },
    // async delete_main(){
    //   const {data:res} =await this.$ajax.post('/api/college/deleteGrades',
    //       {grades_sort:this.grades_sort,grades_year:this.find_year})
    //   console.log(res.code);
    //   if(res.code===1){
    //     this.$msg.success("删除成功！");
    //   }
    //   else{
    //     this.$msg.error("删除失败！");
    //   }
    //   this.init();
    //
    // },






  },
  created() {

    this.grades_sort=1;
    this.$router.push({
      path:'/Main/Colleges_Main/College_Grade/Academic_Grades',
      query:{
        grades_year:this.find_year,
        grades_sort:this.grades_sort,
      }

    });

    let _this=this;
    _this.init();


  }
}
</script>

<style scoped>
.main{
  /*padding-left: 150px;*/
  position: relative;
}
/*选项卡的字体*/
.titlefontclass{
  font-size: 20px;
  font-weight: bold;
}
.titlefontclass:hover{
  color: #0f5da2;
}

</style>
